import { Component, ViewEncapsulation } from '@angular/core';
import { LoginService } from 'views/Login/Login.service';
import { ApiRequest } from 'service/ApiRequest';
import { HttpService } from 'service/HttpService';
import { AuthService } from 'service/AuthService';

import { getLocalItem } from 'utils';

@Component({
    selector: 'header-menu',
    templateUrl: './Header.html',
  }
)

export class HeaderComponent {

  private auth: any = getLocalItem('auth');
  private user: any;

  constructor(private loginService:LoginService, private apiRequest:ApiRequest,private httpService:HttpService,private authService: AuthService) {
  }

  ngOnInit() {
    if(this.auth){
      this.getSelfUserProfileForManage();
    }

    this.loginService.emit.subscribe((login:boolean)=>{
      if(login) {
        this.getSelfUserProfileForManage();
      } else {
        this.user = null;
      }
    });

    this.httpService.emit.subscribe((login:boolean)=>{
      if(!login) {
        this.user = null;
      }
    });
  }

  getSelfUserProfileForManage() {
    this.apiRequest.getSelfUserProfileForManage().then((data) => {
      if(data){
        this.user = data;
        this.authService.setUserInfo(data);
      }
    }).catch((e) => {
      console.log(e);
    });
  }

  logout() {
    this.loginService.emit.emit(false);
    this.loginService.loginOut();
  }

  ngOnDestroy() {
    this.loginService.emit.unsubscribe();
  }
}
